package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author tian
 * @TIME 2023/1/5 10:59 上午
 * @description 短信服务实现类
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendValidateCode(String validateCodeType, String telephone) {
        log.info("[短信-发送验证码]type:{},telephone:{}", validateCodeType, telephone);
        //生成验证码（1000-9999）
        int code = (int) (1000 + Math.random() * 8999);
        log.info("[短信-发送验证码]code:{}", code);
        //保存到Redis
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + validateCodeType + ":" + telephone;
        log.info("redisKey:{}", redisKey);
        redisTemplate.boundValueOps(redisKey).set(String.valueOf(code), 5 * 60L, TimeUnit.SECONDS);
        //阿里云发送验证码
    }

    @Override
    public boolean checkValidateCode(String validateCodeType, String telephone, String validateCode) {
        log.info("[校验短信验证码]validateCodeType:{},telephone:{},validateCode:{}", validateCodeType, telephone, validateCode);
        //构造Redis的key
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + validateCodeType + ":" + telephone;
        //查询Redis里的值
        String redisVal = (String) redisTemplate.boundValueOps(redisKey).get();
        //校验是否匹配
        if (!StringUtils.isEmpty(redisVal) && redisVal.equals(validateCode)) {
            //如果匹配则删除Redis里的记录并返回true
            redisTemplate.delete(redisKey);
            return true;
        }
        //如果不匹配则返回false
        return false;
    }
}
